package com.thb.pay.core.holder;

import java.util.HashMap;
import java.util.Map;

/**
 * @类名称 OperatorLogContextHolder
 * @类描述 <pre></pre>
 * @作者 lucky
 * @创建时间 2019/10/12
 * @版本 v1.01
 */
public class OperatorLogContextHolder {

    private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL_CONTEXTS = new ThreadLocal<>();

    public static Map<String, Object> currentContextMap() {
        Map<String, Object> context = THREAD_LOCAL_CONTEXTS.get();

        if (context == null) {
            context = initContextMap();
        }
        return context;
    }

    protected static Map<String, Object> initContextMap() {
        Map<String, Object> context = new HashMap<>();
        THREAD_LOCAL_CONTEXTS.set(context);
        return context;
    }

    public static boolean has(String key) {
        return currentContextMap().containsKey(key);
    }

    public static <T> T get(String key, Class<T> valueClass) {
        Map<String, Object> currentContextMap = currentContextMap();
        if (currentContextMap.containsKey(key)) {
            Object o = currentContextMap.get(key);
            if (valueClass.isInstance(o)) {
                return valueClass.cast(o);
            }
        }
        return null;
    }

    public static <T> void set(String key, T value) {
        Map<String, Object> context = currentContextMap();
        if (context.containsKey(key)) {
            context.remove(key);
        }

        context.put(key, value);
    }

    public static void delete(String key) {
        Map<String, Object> currentContextMap = currentContextMap();
        if (currentContextMap.containsKey(key))
            currentContextMap.remove(key);
    }

    public static void removeCurrentContextMap() {
        THREAD_LOCAL_CONTEXTS.remove();
    }
}
